class WorkItemsController < ApplicationController

  def index
    @event = Event.find(:first)
    if params[:event_id]
      @event = Event.find(params[:event_id])
    end
#    @must_work_items = event.must_work_items
#    @custom_work_items = event.must_work_items
  end
  
  #创建工作项
  def create
    if params[:event] && params[:work_item]
      work_item = Custom_WorkItem.new(params[:work_item])
      event = Event.find(params[:event])
      work_item.event = event;
      if work_item.save
        redirect_to event_work_items_path(:event_id=>event.id)
      end
    end
  end

  #删除工作项
  def destroy
    work_item = WorkItem.find(params[:id])
    if work_item.destroy
      render :update do |page|
        page.remove("work_item_#{work_item.id}")
      end
    end
  end

  #创建任务
  def create_task
    @work_item = WorkItem.find(params[:work_item])
    @task = Task.new(params[:task])
    @task.work_item = @work_item
    @task.save
  end

  #给任务排序
  def sort_tasks
    arr = params[:id].split(',')
    work_item = WorkItem.find(arr[0])
    if arr[1]=="completed"
      @tasks = work_item.completed_tasks;
      @list_name = "work_item_#{work_item.id}_completed_list"
    else
      @tasks = work_item.uncompleted_tasks
      @list_name = "work_item_#{work_item.id}_uncompleted_list"
    end
    @tasks.each do |todo|
      todo.position=params[@list_name].index(todo.id.to_s) + 1
      todo.save
    end
    render :nothing=>true
  end

  #标记指定任务的完成情况
  def mark_task
    @task = Task.find(params[:id])
    if @task.completed==1
      @task.completed=0
    else
      @task.completed=1
    end
    @task.save
  end

  #删除任务
  def destroy_task
    @task=Task.find(params[:id])
    if @task.destroy
      render :update do |page|
        page.remove("task_#{@task.id}")
      end
    end
  end
end
